package com.chenqi.myblog.controller;

import com.chenqi.myblog.model.Blog;
import com.chenqi.myblog.model.Type;
import com.chenqi.myblog.service.BlogService;
import com.chenqi.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @program: myblog
 * @author: ChenQi
 * @create: 2021-02-2021/2/2-17-15
 */
@Controller
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    /**
     * 分类列表
     * @param tid
     * @param modelAndView
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "tid",required = false) Integer tid,
                             ModelAndView modelAndView) {
        //分类预处理
        tid = tid == null ? 1 : tid;
        List<Type> types = typeService.findAllType();
        List<Type> newTypes = new ArrayList<>();
        for (Type type : types) {
            Integer count = typeService.findTypeCountByBlog(type.getId());
            type.setTotal(count);
            newTypes.add(type);
        }
        List<Blog> blogs = blogService.findByTypeId(tid);
        modelAndView.addObject("blogs", blogs);
        modelAndView.addObject("activeTypeId", tid);
        modelAndView.addObject("types", newTypes);
        modelAndView.setViewName("types");
        return modelAndView;
    }
}
